import random
import string
from app.coupon.model import CouponCode
from app.user.model import User
from common import errors
from common.mixins import DictMixin
from exts import db
from app.coin.service import add_coins_by_use_coupon
from common import constant
from flask import g


def verify_code(company_id, user_id, code):
    coupon_code = CouponCode.query.filter_by(code=code).first()

    if not coupon_code:
        raise errors.BadRequestError("兑换码不存在")
    if coupon_code.is_used:
        raise errors.BadRequestError('兑换码已使用')

    user = User.query.filter_by(id=user_id).first()

    # 消费兑换码
    coupon_code.is_used = True
    coupon_code.consumer_user_id = user.id

    # 积分记录
    add_coins_by_use_coupon(company_id, user_id, coupon_code.coins, coupon_code.code)
    db.session.commit()


def create_coupon_code(id, length=10):
    """
    id + L + 随机码
    string模块中的3个函数：string.letters，string.printable，string.printable
    """
    prefix = hex(int(id))[2:] + 'L'
    length = length - len(prefix)
    chars = string.digits  # string.ascii_letters + string.digits
    return prefix + ''.join([random.choice(chars) for i in range(length)])


def get_id(code):
    id_hex = code.split('L')[0]
    return int(id_hex.upper(), 16)


def create_coupon_script():
    for i in range(12, 20):
        code = create_coupon_code(i)
        code_id = get_id(code)
        CouponCode.create(id=code_id, code=code, coins=constant.CouponCoinType.one)
    db.session.commit()


if __name__ == '__main__':
    from app import create_app

    app = create_app("default")
    # app = create_app("online_test")
    # app = create_app("production")
    with app.app_context():
        g.company_id = None
        g.user_id = None
        create_coupon_script()
